<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <!-- <el-form-item label="课程名称" prop="courseId">
        <el-input
          v-model="queryParams.courseId"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="课程名称" prop="courseId">
        <el-select v-model="queryParams.courseId" placeholder="请输入课程名称" clearable>
          <el-option
            v-for="item in courseOptions"
            :key="item.courseId"
            :label="item.courseName"
            :value="item.courseId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户名" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请输入用户名" clearable>
          <el-option
            v-for="item in userOptions"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="打卡日期">
        <el-date-picker
          v-model="daterangeCheckDatetime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="打卡状态" prop="checkState">
        <el-select v-model="queryParams.checkState" placeholder="请选择打卡状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_attendance"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="float: right;">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:fitnesscheckins:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:fitnesscheckins:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:fitnesscheckins:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:fitnesscheckins:export']"
        >导出</el-button>
      </el-col> 
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-claim"
          size="mini"
          @click="handleCheckins"
          v-hasPermi="['system:fitnesscheckins:checkins']"
        >今日打卡</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table v-loading="loading" :data="fitnesscheckinsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" type="index" />
      <!-- <el-table-column label="课程名称" align="center" prop="courseId" width="100"/> -->
      <el-table-column label="课程名称" align="center" prop="courseId" >
        <template slot-scope="scope">
          <span>{{ scope.row.courseId?courseOptions.find(item => item.courseId == scope.row.courseId).courseName:'' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" align="center" prop="userId" >
        <template slot-scope="scope">
          <span>{{ scope.row.userId?userOptions.find(item => item.userId == scope.row.userId).nickName:'' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="打卡日期" align="center" prop="checkDatetime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.checkDatetime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="卡路里消耗" align="center" prop="checkCaloriesBurned" />
      <el-table-column label="训练时长(min)" align="center" prop="checkTrantime" width="120"/>
      <el-table-column label="打卡状态" align="center" prop="checkState">
        <template slot-scope="scope">
          <template v-if="scope.row.checkState === 'attendance1'">
            <dict-tag :options="dict.type.sys_attendance" style="color:#18e718" :value="scope.row.checkState"/>
          </template>
          <template v-if="scope.row.checkState === 'attendance2'">
            <dict-tag :options="dict.type.sys_attendance" style="color:#F56C6C" :value="scope.row.checkState"/>
          </template>
          <!-- <dict-tag :options="dict.type.sys_attendance" :value="scope.row.checkState"/> -->
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="checkComment" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:fitnesscheckins:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:fitnesscheckins:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改健身打卡信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- <el-form-item label="课程名称" prop="courseId">
          <el-input v-model="form.courseId" placeholder="请输入课程名称" />
        </el-form-item> -->
        <el-form-item label="课程名称" prop="courseId">
              <el-select v-model="form.courseId" placeholder="请输入课程名称" clearable style="width: 100%;">
                <el-option
                  v-for="item in courseOptions"
                  :key="item.courseId"
                  :label="item.courseName"
                  :value="item.courseId"
                />
              </el-select>
            </el-form-item>
        <el-form-item label="用户名" prop="userId">
              <el-select v-model="form.userId" placeholder="请输入用户名" clearable style="width: 100%;">
                <el-option
                  v-for="item in userOptions"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
        <el-form-item label="打卡日期" prop="checkDatetime" >
          <el-date-picker clearable
            v-model="form.checkDatetime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择打卡日期" style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="卡路里消耗" prop="checkCaloriesBurned">
          <el-input v-model="form.checkCaloriesBurned" placeholder="请输入卡路里消耗" />
        </el-form-item>
        <el-form-item label="训练时长(min)" prop="checkTrantime">
          <el-input v-model="form.checkTrantime" placeholder="请输入训练时长(min)" />
        </el-form-item>
        <el-form-item label="打卡状态" prop="checkState">
          <el-select v-model="form.checkState" placeholder="请选择打卡状态" style="width: 100%;">
            <el-option
              v-for="dict in dict.type.sys_attendance"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="checkComment">
          <el-input v-model="form.checkComment" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-calendar :first-day-of-week="7">
      <template slot="dateCell" slot-scope="{ data }">
        <p>{{ data.day.split("-").slice(2).join("-") }}<br/></p>
        <div
            v-for="(item, index) in fitnesscheckinsList"
            :key="index">
            <div v-if="data.day == item.checkDatetime" style="background-color: #18e718;">
                打卡成功
            </div>
          </div>
      </template>
    </el-calendar>
  </div>
</template>

<script>
import { listFitnesscheckins, getFitnesscheckins, delFitnesscheckins, addFitnesscheckins, updateFitnesscheckins } from "@/api/system/fitnesscheckins";
import { listUser } from "@/api/system/user"
import { listCourses } from "@/api/system/courses"

export default {
  name: "Fitnesscheckins",
  dicts: ['sys_attendance'],
  data() {
    return {
      //用户名
      userOptions:[],
      //课程名称
      courseOptions:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 健身打卡信息表格数据
      fitnesscheckinsList: [],
      //用户信息
      sysUserList:[],
      courseList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeCheckDatetime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseId: null,
        userId: null,
        checkDatetime: null,
        checkState: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        courseId: [
          { required: true, message: "课程ID不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getUsers();
    this.getCourse();
  },
  methods: {
    /**查询课程名称 */
    getCourse(){
      const params = {
        pageNum:1,
        pageSize:0,
      }
      listCourses(this.queryParams).then(response => {
        this.courseOptions = response.rows;
      });
    },
    /** 查询用户信息 */
    getUsers(){
      const params = {
        pageNum:1,
        pageSize:0,
      }
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userOptions = response.rows
        }
      );
    },
    /** 查询健身打卡信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCheckDatetime && '' != this.daterangeCheckDatetime) {
        this.queryParams.params["beginCheckDatetime"] = this.daterangeCheckDatetime[0];
        this.queryParams.params["endCheckDatetime"] = this.daterangeCheckDatetime[1];
      }
      listFitnesscheckins(this.queryParams).then(response => {
        this.fitnesscheckinsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        checkId: null,
        courseId: null,
        userId: null,
        checkDatetime: null,
        checkCaloriesBurned: null,
        checkTrantime: null,
        checkState: null,
        checkComment: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null
      };
      this.sysUserList = [];
      this.courseList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCheckDatetime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.checkId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加健身打卡信息";
    },
    handleCheckins(){
      var now = new Date();
      const params ={
        userId:this.$store.state.user.id,
        // courseId: 1,
        checkDatetime:now,
        checkState:"attendance1",
      }
      addFitnesscheckins(params).then(response => {
        this.$modal.msgSuccess("健身打卡成功");
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const checkId = row.checkId || this.ids
      getFitnesscheckins(checkId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改健身打卡信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.checkId != null) {
            updateFitnesscheckins(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFitnesscheckins(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const checkIds = row.checkId || this.ids;
      this.$modal.confirm('是否确认删除健身打卡信息编号为"' + checkIds + '"的数据项？').then(function() {
        return delFitnesscheckins(checkIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/fitnesscheckins/export', {
        ...this.queryParams
      }, `fitnesscheckins_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
